﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

namespace JetBlack.AuthFeedBus.ExcelAddin
{
    [RunInstaller(true)]
    public partial class ExcelAddinInstaller : System.Configuration.Install.Installer
    {
        public ExcelAddinInstaller()
        {
            InitializeComponent();
        }

        private enum TargetPlatform
        {
            x86,
            x64,
            Itanium
        }

        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
            RegAsm("/codebase", GetTargetPlatform());
        }

        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            base.Uninstall(savedState);
            RegAsm("/u", GetTargetPlatform());
        }

        private TargetPlatform GetTargetPlatform()
        {
            TargetPlatform targetPlatform;
            if (System.Enum.TryParse<TargetPlatform>(Context.Parameters["TargetPlatform"] ?? String.Empty, true, out targetPlatform))
                return targetPlatform;
            else
                return TargetPlatform.x86;
        }

        private static void RegAsm(string parameters, TargetPlatform targetPlatform)
        {
            var dotNetBase = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), @"..\.."));

            string frameworkDir;
            switch (targetPlatform)
            {
                case TargetPlatform.x64:
                    frameworkDir = "Framework64";
                    break;
                case TargetPlatform.x86:
                    frameworkDir = "Framework";
                    break;
                case TargetPlatform.Itanium:
                default:
                    throw new ArgumentException("Unhandled target platform");
            }

            var regasmPath = Path.Combine(dotNetBase, frameworkDir, RuntimeEnvironment.GetSystemVersion(), "regasm.exe");

            var process = new Process
            {
                StartInfo =
                {
                    CreateNoWindow = true,
                    ErrorDialog = false,
                    UseShellExecute = false,
                    FileName = regasmPath,
                    Arguments = string.Format("\"{0}\" {1}", Assembly.GetExecutingAssembly().Location, parameters)
                }
            };

            using (process)
            {
                process.Start();
                process.WaitForExit();
            }
        }

    }
}
